package com.prs.crm.service.sys.impl;

import java.util.Collection;
import java.util.List;

import com.prs.crm.dao.sys.MenuDao;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.sys.Menu;
import com.prs.crm.service.impl.BaseServiceImpl;
import com.prs.crm.service.sys.MenuService;

public class MenuServiceImpl extends BaseServiceImpl<Menu,MenuDao> implements MenuService{

	
	public 	Collection<Menu> getShortCutMenus()
	{
		return this.getDao().getShortCutMenus();
	}
	
	@Override
	public void save(Menu menu)
	{
		if (menu.getSequence()==null)
		{
		  Integer maxsequence = this.getDao().getMaxSequence(menu.getParent());
		  menu.setSequence((maxsequence==null)?1:(maxsequence+1));
		}
		super.save(menu);
	}
	
	
	@Override
	public void remove(Menu menu)
	{
		Menu parent = menu.getParent();
		super.remove(menu);
		this.resetSequence(parent);
	}
	
	public 	List<Menu> getRootMenus()
	{
		return this.getDao().getRootMenus();
	}
	
	public void adjustUp(Menu menu)
	{
		if (menu.getSequence()>1)
		{
			Menu prev = this.getDao().findFirstBeforeMenu(menu.getParent(), 
					menu.getSequence());
			if (prev!=null)
			{
				Integer prevsequence = prev.getSequence();
				prev.setSequence(menu.getSequence());
				menu.setSequence(prevsequence);
				super.save(prev);
			}
			
		}
		super.save(menu);
	}
	
	
	public void adjustDown(Menu menu)
	{
		Menu next = this.getDao().findFirstAfterMenu(menu.getParent(), 
				menu.getSequence()+1);
		if (next!=null)
		{
			Integer nextsequence = next.getSequence();
			next.setSequence(menu.getSequence());
			menu.setSequence(nextsequence);
			super.save(next);
			super.save(menu);
		}
		
	}
	
	public Collection<Menu> findMenus(Menu parent,Person person)
	{
		return this.getDao().findMenus(parent,person);
	}


	@Override
	public Collection<Menu> getChildMenu(Menu menu) {
		return this.getDao().getChildMenu(menu);
	}
	
	public void resetSequence(Menu parent)
	{
		Collection<Menu> menus = this.getChildMenu(parent);
		int sequence = 1;
		for (Menu menu : menus)
		{
			menu.setSequence(sequence++);
			this.save(menu);
		}
	}
	/**
	 * 批量删除
	 * 
	 * JohnLan
	 */
	public boolean bachDelMenu(Integer[] ids) {
	
		return this.getDao().bachDelMenu(ids);
	}

	@Override
	public List getCurrentOb(String sql) {
		// TODO Auto-generated method stub
		return this.getDao().getCurrentOb(sql);
	}

	@Override
	public Integer delData(String hql) {
		// TODO Auto-generated method stub
		return this.getDao().delData(hql);
	}

	@Override
	public List<Menu> getAllMenu() {
		return this.getDao().getAllMenu();
	}
}
